/*
 * @(#)LogonAction.java 1.0 11/01/18
 *
 * Copyright 2011 YiChang Ewolf Information Technology Co.,Ltd, All rights reserved.
 */

package cn.org.timespace.easyframe.action;

import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import cn.org.timespace.easyframe.model.permission.EfMenu;
import cn.org.timespace.easyframe.model.permission.EfUser;
import cn.org.timespace.easyframe.model.permission.SystemMessage;
import cn.org.timespace.easyframe.service.permission.EfControlPointService;
import cn.org.timespace.easyframe.service.permission.EfMenuService;
import cn.org.timespace.easyframe.service.permission.EfMenuShortcutService;
import cn.org.timespace.easyframe.service.permission.EfUserLoginLogService;
import cn.org.timespace.easyframe.service.permission.EfUserService;
import cn.org.timespace.easyframe.service.permission.SystemMessageService;
import cn.org.timespace.easyframe.util.EfResourceContext;
import cn.org.timespace.easyframe.util.web.Security;

import com.opensymphony.xwork2.ActionContext;

/**
 * <p>
 * 登录类
 * </p>
 * 
 * @version 1.0, 11/01/18
 * @since 1.0
 * @author 
 */

public class EfLogonAction extends EFBaseAction {

	private static final long serialVersionUID = -3224275471309009166L;
	private static Log log = LogFactory.getLog(EfLogonAction.class);
	
	private static final String SELECT = "select";
	private static final String INDEX_FOR_NOT_SELECT = "indexForNotSelect";

	private static final String PERMISSION_INDEX = "permissionIndex";
	
	private static final String LOGON_TYPE_SELECT = "select";
	private static final String LOGON_TYPE_ORI = "ori";
	
	//用户
	private EfUserService efUserService;
	//菜单
	private EfMenuService efMenuService;
	//快捷菜单
	private EfMenuShortcutService efMenuShortcutService;
	//用户登录日志
	private EfUserLoginLogService efUserLoginLogService;
	//系统公告
	private SystemMessageService systemMessageService;
	//控制点
	private EfControlPointService efControlPointService;
	
	public SystemMessageService getSystemMessageService() {
		return systemMessageService;
	}

	public void setSystemMessageService(SystemMessageService systemMessageService) {
		this.systemMessageService = systemMessageService;
	}

	// 该构造函数必须这样实现
	public EfLogonAction() {
		super(new EfLogonModel());
	}
	
	//登录
	public String execute() throws Exception {
		
		String logonType = EfResourceContext.getInstance().getParamValue("logon.type");
		
		if(log.isInfoEnabled()) log.info("正在执行登录请求...，当前登录类型为："+logonType);
		
		EfLogonModel logonModel = (EfLogonModel) this.getModel();

		// 第一步： 判断验证码是否正确
		if (!verifyAuthCode(logonModel.getAuthCode())){
			return EfActionConstant.RELOGON;
		}
		
		if(log.isInfoEnabled()) log.info("正在执行登录请求...，正在进行用户名和密码验证");
		
		// 第二步： 判断用户名和密码是否正确
		EfUser efUser = new EfUser();
		efUser.setUserAccount(logonModel.getUserAccount());
			//密码要MD5
		efUser.setUserPassword(Security.encrypt(logonModel.getUserPassword()));
		
		efUser = efUserService.authentication(efUser);
		if (efUser == null){
			String errorMsg = getText("error.LogonModel.userIdAndPassword.notFound");
			if(log.isErrorEnabled()) log.error(errorMsg);
			ServletActionContext.getRequest().setAttribute(EfActionConstant.GLOBAL_ERRMSG_TOPAGE,errorMsg);
			
			return EfActionConstant.RELOGON;
		}
		
		if(log.isInfoEnabled()) log.info("正在执行登录请求...，正在记录登录日志");
		//记录登录日志
		//writeUserLogonLog("成功登录！",efUser.getUserId());
		efUserService.writeUserLogonLog("成功登录！",efUser.getUserId(), getRequest().getRemoteHost());
		
		if(log.isInfoEnabled()) log.info("正在执行登录请求...，正在将当前用户信息添加到session");
		//将该登录对象添加到Session
		EfUserSession efUserSession = new EfUserSession();
		efUserSession.setEfUser(efUser);
		Map httpSession = ActionContext.getContext().getSession();
		httpSession.put(SESSION_KEY, efUserSession);
		
		if(log.isInfoEnabled()) log.info("正在执行登录请求...，正在获取该用户的控制点，并添加到session");
		//获取该用户的控制点
		Map<String,String> cpMap = efControlPointService.findMapByUserId(getUserId());
		httpSession.put(CONTROL_POINT_KEY, cpMap);
		if(log.isDebugEnabled()) log.debug("正在执行登录请求...，当前用户的控制点有："+cpMap);
		
		if(logonType.equals(LOGON_TYPE_SELECT))
		{
			//第三步：获取最顶层(模块)菜单
			List<EfMenu> topMenuList = efMenuService.findTopLevelMenu(getUserId());
			getRequest().setAttribute("topMenuList", topMenuList);
			
			return SELECT;
		}
		else if(logonType.equals(LOGON_TYPE_ORI))
		{
			List<EfMenu> topMenuList = efMenuService.findTopLevelMenu();
			getRequest().setAttribute("topMenuList", topMenuList);
			
			List<EfMenu> secondMenuList = efMenuService.findSecondLevelMenu();
			getRequest().setAttribute("secondMenuList", secondMenuList);
			
			return INDEX_FOR_NOT_SELECT;
		}
		
		return EfActionConstant.RELOGON;
	}
	
	//进入模块选择
	public String doEnterModelSelect() throws Exception {
		
		//第一步：获取最顶层(模块)菜单
		List<EfMenu> topMenuList = efMenuService.findTopLevelMenu(getUserId());
		getRequest().setAttribute("topMenuList", topMenuList);
		
		return SELECT;
		
	}
	
	//进入模块首页
	public String doEnterModel() throws Exception {
		
		
		// 第一步： 获取当前用户跟当前模块
		String modelId = getRequest().getParameter("modelId");
		getRequest().setAttribute("modelId", modelId);
		String menuname = getRequest().getParameter("menuname");
		getRequest().setAttribute("menuname", menuname);
		// 第二步：获取最顶层(模块)菜单
		List<EfMenu> topMenuList = efMenuService.findSecondLevelMenu(getUserId(), modelId);
		getRequest().setAttribute("secondMenuList", topMenuList);
		// 第三步：获取模块下属菜单
		List<EfMenu> thirdMenuList = efMenuService.findThirdLevelMenu(getUserId(), modelId);
		getRequest().setAttribute("thirdMenuList", thirdMenuList);
		if(thirdMenuList!=null&&thirdMenuList.size()>0){
			getRequest().setAttribute("oneMenu", thirdMenuList.get(0).getMenuUrl());
		}
		//第四步：获取快捷菜单
		List<EfMenu> menuList = efMenuShortcutService.findByCondition(getUserId());
		getRequest().setAttribute("menuList", menuList);
		
		//系统公告
		List<SystemMessage> systemMessages=systemMessageService.findValidSystemMessage();
		getRequest().setAttribute("systemMessages", systemMessages);
	
		if(!StringUtils.isEmpty(modelId))
		{
			/*if(modelId.equals("100")){
				return GUESTROOM_INDEX;
			}else if(modelId.equals("200")){
				return RECEPTION_INDEX;
			}else if(modelId.equals("300")){
				return REPAST_INDEX;
			}else if(modelId.equals("400")){
				return NIGHTAUDIT_INDEX;
			}else if(modelId.equals("500")){
				return SALEMANAGER_INDEX;
			}else if(modelId.equals("600")){
				return REPORT_INDEX;
			}else if(modelId.equals("700")){
				return PERMISSION_INDEX;
			}else if(modelId.equals("900")){
				return DEMO_INDEX;
			}*/
		}
		
		//系统管理
		return PERMISSION_INDEX;
	}
	
	/**
	 * 验证验证码是否正确
	 * @return
	 */
	private boolean verifyAuthCode(String inputAuthCode){
		
		String errorMsg = "";
		Object authCodeInSession = ActionContext.getContext().getSession().get("validateCode");
		
		//判断验证码是否存在
		if(authCodeInSession == null){
			errorMsg = getText("error.LogonModel.authCode.notFound");
			if(log.isInfoEnabled()) log.info(errorMsg);
			ServletActionContext.getRequest().setAttribute(EfActionConstant.GLOBAL_ERRMSG_TOPAGE,errorMsg);
			return false;
		}
		
		if(!authCodeInSession.toString().equalsIgnoreCase(inputAuthCode)){
			errorMsg = getText("error.LogonModel.authCode");
			if(log.isErrorEnabled()) log.error(errorMsg);
			ServletActionContext.getRequest().setAttribute(EfActionConstant.GLOBAL_ERRMSG_TOPAGE,errorMsg);
			
			return false;
		}
		
		return true;
	}

	public EfUserService getEfUserService() {
		return efUserService;
	}

	public void setEfUserService(EfUserService efUserService) {
		this.efUserService = efUserService;
	}

	public EfMenuService getEfMenuService() {
		return efMenuService;
	}

	public void setEfMenuService(EfMenuService efMenuService) {
		this.efMenuService = efMenuService;
	}
	
	public EfUserLoginLogService getEfUserLoginLogService() {
		return efUserLoginLogService;
	}

	public void setEfUserLoginLogService(EfUserLoginLogService efUserLoginLogService) {
		this.efUserLoginLogService = efUserLoginLogService;
	}
	
	public EfMenuShortcutService getEfMenuShortcutService() {
		return efMenuShortcutService;
	}

	public void setEfMenuShortcutService(EfMenuShortcutService efMenuShortcutService) {
		this.efMenuShortcutService = efMenuShortcutService;
	}
	
	
	public EfControlPointService getEfControlPointService() {
		return efControlPointService;
	}

	public void setEfControlPointService(EfControlPointService efControlPointService) {
		this.efControlPointService = efControlPointService;
	}
	
	//ajax登陆同步天绎门户
	public String doAjaxLogin() throws Exception {
		Cookie[] cookies = getRequest().getCookies(); 
		//循环取cookies
		for(int i=0;i<cookies.length;i++){
			//用户已登陆
			if(cookies[i].getName().equals("TSONSUserID")){
				String userID = cookies[i].getValue();
				continue;
			}
		}
		return SELECT;
	}
}
